package homework_2;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class ImageCut {
	 private String srcpath = "src/123.jpg";		//源图片存储地址
	 private String subpath = "src/123123.jpg";		//输出图片存储地址
	     
	 private static final String IMAGE_FORM_OF_JPG = "jpg";
	 private static final String IMAGE_FORM_OF_PNG = "png";
	 private int x;
	 private int y;
	 private int width;
	 private int height;
	 
	 public ImageCut() {
	    	  
	     }
	    
	 public ImageCut(int x, int y, int width, int height) {
	    	 this.x = x;
	    	 this.y = y;
	    	 this.width = width;
	    	 this.height = height;
	     }
	    
	    
	 public static void main(String[] args) throws Exception {
	    	 ImageCut imageCut = new ImageCut(134, 0, 366, 366);	//截取以（134，0）为左上角点大小为366*366的图片
	    	 imageCut.cut(imageCut.getSrcpath(), imageCut.getSubpath());
	     }
	 
	 public Iterator<ImageReader> getImageReadersByFormatName(String postFix) {
 
		 switch (postFix) {
		 case IMAGE_FORM_OF_JPG:
			 
			 return ImageIO.getImageReadersByFormatName(IMAGE_FORM_OF_JPG);
			 
		 case IMAGE_FORM_OF_PNG:
			 
			 return ImageIO.getImageReadersByFormatName(IMAGE_FORM_OF_PNG);
			 
		 default:	         
			 return ImageIO.getImageReadersByFormatName(IMAGE_FORM_OF_JPG);
	        }
	   }
	     
	     
	 public void cut(String srcpath, String subpath) throws IOException {
		 FileInputStream is = null;
		 ImageInputStream Input = null;
	     try{
	    	 is = new FileInputStream(srcpath);		//读取文件

	    		 
	    	 Iterator<ImageReader> it = getImageReadersByFormatName("jpg");
	    	 ImageReader reader = it.next();
	    	 Input = ImageIO.createImageInputStream(is);	//创建输入流
	    	 reader.setInput(Input, true);
	    	 ImageReadParam param = reader.getDefaultReadParam();
	    	 //创建一个矩形范围
	    	 Rectangle rect = new Rectangle(x, y, width, height);	    	
	    	 param.setSourceRegion(rect);
	    	 //输出文件
	    	 BufferedImage image = reader.read(0,param);
	    	 ImageIO.write(image, "jpg", new File(subpath));	    	
	     }
	     finally{
	    	 if(is != null)
	    		 is.close();
	    	 if(Input != null)
	    		 Input.close();
	     }
	 }	    	  	     	    	     
	     public String getSrcpath() {	    	        
	    	 return srcpath;	    	     
	     }
	    	  	    	     	    	  	    	     
	     public String getSubpath() {	    	      	    	
	    	 return subpath;
	    	      }   
	     }


	


